package com.mayikt.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mayikt.entity.Ebook;
import com.mayikt.entity.EbookExample;
import com.mayikt.mapper.EbookMapper;
import com.mayikt.req.EbookQueryReq;
import com.mayikt.req.EbookSaveReq;
import com.mayikt.resp.EbookQueryResp;
import com.mayikt.resp.PageResp;
import com.mayikt.utils.CopyUtil;
import com.mayikt.utils.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {
    @Resource
    private EbookMapper ebookMapper;
    @Resource
    private SnowFlake snowFlake;

    /**
     * 查询
     * @param ebookQueryReq
     * @return
     */
    public PageResp<EbookQueryResp> list(EbookQueryReq ebookQueryReq) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();

        // 判断 name 条件是否为空
        if(!ObjectUtils.isEmpty(ebookQueryReq.getName())) {
            criteria.andNameLike("%" + ebookQueryReq.getName() + "%");
        }

        // 判断 二级分类id是否为空
        if(!ObjectUtils.isEmpty(ebookQueryReq.getCategory2Id())) {
            criteria.andCategory2IdEqualTo(ebookQueryReq.getCategory2Id());
        }

        // 分页
        PageHelper.startPage(ebookQueryReq.getPage(), ebookQueryReq.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);

        // do 转 dto
        List<EbookQueryResp> ebookResps = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(ebookResps);

        return pageResp;
    }

    @Transactional
    public int save(EbookSaveReq ebookSaveReq) {
        Ebook ebook = CopyUtil.copy(ebookSaveReq, Ebook.class);
        int result = 0;
        if(ObjectUtils.isEmpty(ebookSaveReq.getId())) {
            // 雪花算法 生成id
            ebook.setId(snowFlake.nextId());
            // 新增
            result = ebookMapper.insertSelective(ebook);
        } else {
            // 更新
            result = ebookMapper.updateByPrimaryKey(ebook);
        }
        return result;
    }

    @Transactional
    public int delete(Long id) {
        return ebookMapper.deleteByPrimaryKey(id);
    }
}
